//
//  BIDPayListViewController.m
//  zkwy
//
//  Created by mal on 2016/11/11.
//  Copyright © 2016年 mal. All rights reserved.
//

#import "BIDPayListViewController.h"
#import "BIDPayRecordViewController.h"
#import "BIDPayCell.h"
#import "BIDPayDetailCell.h"
#import "BIDPayMethodCell.h"
#import "BIDNode.h"
#import "UITableView+BIDHaveEmptyData.h"

#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "RSADataSigner.h"
#import "APAuthV2Info.h"


//普通费用列表
static NSString *normalFeeListURL = @"client/self/list.action";

//停车费
static NSString *parkFeeListURL = @"client/self/gainParkFee.action";

//交费
static NSString *toPayURL = @"client/self/doPay.action";

@interface BIDPayListViewController ()<UITableViewDelegate, UITableViewDataSource, BIDPayCellDelegate, BIDPayMethodCellDelegate, UIAlertViewDelegate>
{
    BOOL _bRegister;
    NSArray *_normalFeeArr;
    NSArray *_parkFeeArr;
    NSArray *_payMethodArr;
    NSMutableArray *_selectStatusArr;
    BIDPayCell *_temporaryCell;
    //选中的总的应交费用
    NSDecimalNumber *_totalAmount;
    //普通费用
    NSMutableArray *_dataSourceArr;
    NSMutableArray *_originalArr;
    //停车费是否选中
    BOOL _isParkFeeChoose;
    //交费方式选中的状态
    NSMutableArray *_payMethodStateArr;
    //选中的支付方式
    NSUInteger _selectPayMethod;
    //是否有被锁定的费用
    BOOL _isHaveLockFee;
}
@end

@implementation BIDPayListViewController
@synthesize houseCode;
@synthesize feeCode;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"费用列表";
    _selectPayMethod = 0;
    _normalFeeArr = [[NSArray alloc] init];
    _selectStatusArr = [[NSMutableArray alloc] init];
    _totalAmount = [NSDecimalNumber decimalNumberWithString:@"0"];
    _temporaryCell = [[[NSBundle mainBundle] loadNibNamed:@"BIDPayCell" owner:self options:nil] lastObject];
    [_tableView setBackgroundColor:[UIColor whiteColor]];
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //_tableView.allowsSelection = NO;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navBar_history.png"] style:UIBarButtonItemStylePlain target:self action:@selector(showPayRecord)];
    //
    [self prepareForData];
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)prepareForData
{
    _isHaveLockFee = NO;
    _isParkFeeChoose = YES;
    NSArray *arr = @[@[], @[]];
    _originalArr = [[NSMutableArray alloc] initWithArray:arr];
    _dataSourceArr = [[NSMutableArray alloc] initWithArray:arr];
    _payMethodStateArr = [[NSMutableArray alloc] initWithObjects:@1, @0, @0, nil];
    //
    //
    _normalFeeArr = [[NSArray alloc] init];
    _parkFeeArr = [[NSArray alloc] init];
    _payMethodArr = @[@{@"logo":@"payMethod_construction.png", @"title":@"建设银行"}, @{@"logo":@"payMethod_ali.png", @"title":@"支付宝"}, @{@"logo":@"payMethod_wechat.png", @"title":@"微信"}];
    //
    if((ISNULL(houseCode)) || (ISNULL(feeCode)))
    {
        NSArray *arr = [AppDelegate getBindingHouse];
        NSDictionary *dic = arr[0];
        self.houseCode = dic[@"houseCode"];
        self.feeCode = dic[@"feeCode"];
    }
}

- (void)reset
{
    _totalAmount = [NSDecimalNumber decimalNumberWithString:@"0"];
    [_selectStatusArr removeAllObjects];
}

- (void)loadData
{
    [self fetchNormalFeeList];
}

/**
 显示缴费记录
 */
- (void)showPayRecord
{
    BIDPayRecordViewController *vc = [[BIDPayRecordViewController alloc] initWithNibName:@"BIDPayRecordViewController" bundle:nil];
    vc.houseCode = self.houseCode;
    vc.feeCode = self.feeCode;
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 获取普通费用列表
 */
- (void)fetchNormalFeeList
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getPayServerAddr], normalFeeListURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"searchParam.houseCode=%@", houseCode];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            _normalFeeArr = [[NSArray alloc] initWithArray:responseDic[@"data"]];
            NSNumber *value = responseDic[@"account"][@"curCost"];
            _totalAmount = [NSDecimalNumber decimalNumberWithString:[[NSString alloc] initWithFormat:@"%.2f", [value floatValue]]];
            _amountLabel.text = [[NSString alloc] initWithFormat:@"总计：￥%@", _totalAmount];
            NSUInteger index = 0;
            NSMutableArray *tempArr = [NSMutableArray array];
            NSMutableArray *tempOriginalArr = [NSMutableArray array];
            for(NSDictionary *dic in _normalFeeArr)
            {
                BIDNode *node = [[BIDNode alloc] init];
                node.parentID = @"rootID";
                node.data = [[NSDictionary alloc] initWithDictionary:dic];
                node.isExpand = NO;
                node.isLeaf = NO;
                node.nodeID = [[NSString alloc] initWithFormat:@"p%ld", index];
                node.level = 1;
                [tempArr addObject:node];
                [tempOriginalArr addObject:node];
                NSString *parentID = node.nodeID;
                index++;
                NSArray *subArr = dic[@"payFeeList"];
                NSUInteger subIndex = 0;
                for(NSDictionary *subDic in subArr)
                {
                    BIDNode *childNode = [[BIDNode alloc] init];
                    childNode.parentID = parentID;
                    childNode.nodeID = [[NSString alloc] initWithFormat:@"sub%ld", subIndex];
                    childNode.data = [[NSDictionary alloc] initWithDictionary:subDic];
                    childNode.isExpand = NO;
                    childNode.isLeaf = YES;
                    childNode.level = 2;
                    subIndex++;
                    [tempOriginalArr addObject:childNode];
                }
            }
            [_dataSourceArr replaceObjectAtIndex:0 withObject:tempArr];
            [_originalArr replaceObjectAtIndex:0 withObject:tempOriginalArr];
        }
        [self fetchParkFeeList];
     }];
}

/**
 获取停车费用列表
 */
- (void)fetchParkFeeList
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getPayServerAddr], parkFeeListURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"searchParam.houseCode=%@", houseCode];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            NSArray *arr = responseDic[@"data"];
            _parkFeeArr = [[NSArray alloc] initWithArray:arr];
            NSMutableArray *tempArr = [NSMutableArray array];
            NSMutableArray *tempOriginalArr = [NSMutableArray array];
            NSUInteger index = 0;
            for(NSDictionary *dic in arr)
            {
                BIDNode *node = [[BIDNode alloc] init];
                node.parentID = @"rootID";
                node.data = [[NSDictionary alloc] initWithDictionary:dic];
                node.isExpand = NO;
                node.isLeaf = NO;
                node.nodeID = [[NSString alloc] initWithFormat:@"p%ld", index];
                node.level = 1;
                [tempArr addObject:node];
                [tempOriginalArr addObject:node];
                NSString *parentID = node.nodeID;
                index++;
                NSArray *subArr = dic[@"payFeeList"];
                NSUInteger subIndex = 0;
                for(NSDictionary *subDic in subArr)
                {
                    BIDNode *childNode = [[BIDNode alloc] init];
                    childNode.parentID = parentID;
                    childNode.nodeID = [[NSString alloc] initWithFormat:@"sub%ld", subIndex];
                    childNode.data = [[NSDictionary alloc] initWithDictionary:subDic];
                    childNode.isExpand = NO;
                    childNode.isLeaf = YES;
                    childNode.level = 2;
                    subIndex++;
                    [tempOriginalArr addObject:childNode];
                }
            }
            [_dataSourceArr replaceObjectAtIndex:1 withObject:tempArr];
            [_originalArr replaceObjectAtIndex:1 withObject:tempOriginalArr];
            [_tableView reloadData];
            //
            if(_normalFeeArr.count==0 && _parkFeeArr.count==0)
            {
                [_tableView showEmptyView];
                _containerView.hidden = YES;
            }
            else
            {
                [_tableView hideEmptyView];
                _containerView.hidden = NO;
            }
        }
    }];
}

/**
 产生随机订单号

 @return <#return value description#>
 */
- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}

/**
 调用支付宝支付
 */
- (void)doAlipayPay
{
    //重要说明
    //这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
    //真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
    //防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *appID = @"2016080500173228";
    
    // 如下私钥，rsa2PrivateKey 或者 rsaPrivateKey 只需要填入一个
    // 如果商户两个都设置了，优先使用 rsa2PrivateKey
    // rsa2PrivateKey 可以保证商户交易在更加安全的环境下进行，建议使用 rsa2PrivateKey
    // 获取 rsa2PrivateKey，建议使用支付宝提供的公私钥生成工具生成，
    // 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
    NSString *rsa2PrivateKey = @"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCSI4ej/gjtBB0/NFfdcbRziwOBLZVgF1z8jy7ORMs1ia9D7CztTFfreBnjsqUHIuZddkv3QriQtIF2J+hI+pljcDdC1KWY+6K3tcu6LSu8z9bkC+ArG2urfcx+vh6ZAWdvaFxutj/HzjWwimDj1saCtYU6KJHDG84yOHPpzpDasRsgR+znucFpHnoZmQ1ORCPNI+yZpbpMWaxKsqfFBr8YWp16QQhAs+/Glz2ytPVFtp9g9oX2TlVpVJdg3p8POSrr556PXDHuwUmBY7xssDL204TOSphAnDAvLBLs7npuF7NSA2rcroQmvqiMJEx2Owux4D9HmpV8cnQ1HeA3o8VfAgMBAAECggEAZji4HnwJnlDsbFOeymVIxjGNCATsocR15Kv7H4l7Yz2l/Srs2ig2r5zY7y78xJsi7GldBd4D4CSDEjUkBDhWpvnNjc/U7cfGsB5YHSiPmYkAVZABA+YwUEq0iktOd9RFl+Y2EbMltguF/rEsyPJo9PEn+eB65TFD8FkQq5E0PePhAcatyF9GAdfl3e5D2zmuOWkX+1gEFtIDpmQFjjHuoEGW6QwEB/9Yjse9Kl9VzbIhlg5JmPur/jJz/vAL9nNaWCxr8ylSsuEQRXFHFhgggXoXCedwtq+wACt6lFYL8XaJrYETQFeIaB8WJLNusTX8hAi5Xi+rxXv7/yHiE/xowQKBgQD550yHlOq12lmw167Gl+LbtWrlMuBunt7BKhECi9GXROBnQmTO5PMtok+a0SrRo30IKtedm2zgen/cF9UnHh1WvA2p+nUPCVdnpiqsulN7/aWrogFz2jm9dZWisDwNYXRzMBGJbp89LqfsYb+p3hsu3f1j8nrgW/CV22tu1xAtLwKBgQCVtDKsMd24BR/9/1wK83b5eCtM3nHBlPyEwIO8VJuJDKY12JiuKV++O2AQDi2xrxHHJZd0U5G3n1+ov52piiiXITdK1zGZdoUa+IKPalmj1Q5OBV72atPXUrb66PBMr1eQew51EtFAsbS0e48iw4XKY0w5/oEIXJAzdifjHvq+0QKBgQCMV/Zlqh8KE98M7oOr6f6wTrkCkMjztur4Zix5VpZVMown0WSVwIRFG4NDObanVv5PyOegDnpdss39h7DgMAxf+mpeDFcTI7bfcbVDnbxmxLL2qZvROTv2B4QKgpinFxTz34npuaNaE8qgeODPf/maH3c/WxzgxSFet4QlEkh2ZwKBgDwJj4TlXsENNR5dSeGOcHluCxeB4mc7Q+ZNeseNuu7EpufTXLAEIcSd9VGbDhJDXsLaPZpGZZsZjHiVmDpFETBC/vTBxr9/+7OsVFgF07tTl7AMkWALybeCEaYgwzZN37Uu1MZ47HigjBMRtn6/oSlgl1Ju0fqzfJVW3npEk1TxAoGAI+ZSWjcLwCKKghT7vlyVK6y40FvgkWAzLLoDDwRrRuIh+b/e6DqRvtTLOpzwtab3rD/72ZCAmOI17XjlXh5HLK4mALGDzNclFNY5BMxrVqy+r+vEfamdylwcjTtQovprj+sxwWdPl6IS0PoGCXhMMeQmp1P2ElYcrTOhfmiOwD4=";
    NSString *rsaPrivateKey = @"";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([appID length] == 0 ||
        ([rsa2PrivateKey length] == 0 && [rsaPrivateKey length] == 0))
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少appId或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order* order = [Order new];
    
    // NOTE: app_id设置
    order.app_id = appID;
    
    // NOTE: 支付接口名称
    order.method = @"alipay.trade.app.pay";
    
    // NOTE: 参数编码格式
    order.charset = @"utf-8";
    
    // NOTE: 当前时间点
    NSDateFormatter* formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    order.timestamp = [formatter stringFromDate:[NSDate date]];
    
    // NOTE: 支付版本
    order.version = @"1.0";
    
    // NOTE: sign_type 根据商户设置的私钥来决定
    order.sign_type = (rsa2PrivateKey.length > 1)?@"RSA2":@"RSA";
    
    // NOTE: 商品数据
    order.biz_content = [BizContent new];
    order.biz_content.body = @"我是测试数据";
    order.biz_content.subject = @"1";
    order.biz_content.out_trade_no = [self generateTradeNO]; //订单ID（由商家自行制定）
    order.biz_content.timeout_express = @"30m"; //超时时间设置
    order.biz_content.total_amount = [NSString stringWithFormat:@"%.2f", 0.01]; //商品价格
    
    //将商品信息拼接成字符串
    NSString *orderInfo = [order orderInfoEncoded:NO];
    NSString *orderInfoEncoded = [order orderInfoEncoded:YES];
    NSLog(@"orderSpec = %@",orderInfo);
    
    // NOTE: 获取私钥并将商户信息签名，外部商户的加签过程请务必放在服务端，防止公私钥数据泄露；
    //       需要遵循RSA签名规范，并将签名字符串base64编码和UrlEncode
    NSString *signedString = nil;
    RSADataSigner* signer = [[RSADataSigner alloc] initWithPrivateKey:((rsa2PrivateKey.length > 1)?rsa2PrivateKey:rsaPrivateKey)];
    if ((rsa2PrivateKey.length > 1)) {
        signedString = [signer signString:orderInfo withRSA2:YES];
    } else {
        signedString = [signer signString:orderInfo withRSA2:NO];
    }
    
    // NOTE: 如果加签成功，则继续执行支付
    if (signedString != nil) {
        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
        NSString *appScheme = @"hjgjCommunity";
        
        // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
        NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
                                 orderInfoEncoded, signedString];
        
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
        }];
    }
}
/**
 缴费,需要判断是否有被锁定的费用（被锁定的费用不能缴费，需要管理员确定后更改费用状态和解锁）

 @param sender <#sender description#>
 */
- (IBAction)toPay:(id)sender
{
    if(_isHaveLockFee)
    {
        [self showAlertView:@"有被锁定的费用，请联系管理员解锁后再缴纳。" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    switch(_selectPayMethod)
    {
        case 0:
        {
            //建行卡，直接往下走
        }
            break;
        case 1:
        {
            //支付宝
            //[self doAlipayPay];
            return;
        }
            break;
        case 2:
        {}
            break;
    }
    //
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getPayServerAddr], toPayURL];
    NSMutableString *strPost = [[NSMutableString alloc] initWithFormat:@"payRecord.chargeUser=%@&payRecord.houseCode=%@&payRecord.payAmount=%@&payRecord.payType=%@&payRecord.feeType=%@&payRecord.feeCode=%@", [AppDelegate getUserId], houseCode, _totalAmount, @"mobile", @0, feeCode];
    NSMutableString *strTemp = [NSMutableString string];
    int count = 0;
    for(BIDNode *node in _dataSourceArr[0])
    {
        NSDictionary *dic = node.data;
        NSArray *detailFeeArr = dic[@"payFeeList"];
        for(int j=0; j<detailFeeArr.count; j++)
        {
            NSDictionary *detailFeeDic = detailFeeArr[j];
            NSString *str = [[NSString alloc] initWithFormat:@"payRecord.items[%d].id=%@", count, detailFeeDic[@"id"]];
            [strTemp appendFormat:@"&%@", str];
            count++;
        }
    }
    if(_isParkFeeChoose)
    {
        for(BIDNode *node in _dataSourceArr[1])
        {
            NSDictionary *dic = node.data;
            NSArray *detailFeeArr = dic[@"payFeeList"];
            for(int j=0; j<detailFeeArr.count; j++)
            {
                NSDictionary *detailFeeDic = detailFeeArr[j];
                NSString *str = [[NSString alloc] initWithFormat:@"payRecord.items[%d].id=%@", count, detailFeeDic[@"id"]];
                [strTemp appendFormat:@"&%@", str];
                count++;
            }
        }
    }
    if(strTemp.length > 0)//有缴费参数时说明有费用可以缴纳
    {
        [strPost appendString:strTemp];
        self.bManualHandleHTTPFailed = YES;
        [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
            if(errMsg)
            {
                [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
            }
            else if(responseDic)
            {
                NSString *err = responseDic[@"error"];
                NSString *strMsg = [[NSString alloc] initWithFormat:@"交费失败：%@", err];
                [self showAlertView:strMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
            }
            else
            {
                [self showAlertView:@"缴费成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler"];
            }
        }];
    }
    else
    {
        NSArray *arr1 = _dataSourceArr[0];
        NSArray *arr2 = _dataSourceArr[1];
        if(arr1.count==0 && arr2.count==0)
        {
            [BIDGlobalMethods showAlertView:@"没有费用需要交纳" buttonTitle:@"关闭" delegate:nil tag:0];
        }
        else if(arr2.count>0 && !_isParkFeeChoose)
        {
            [BIDGlobalMethods showAlertView:@"请先选中要交纳的费用" buttonTitle:@"关闭" delegate:nil tag:0];
        }
    }
}


/**
 重新组合数据

 @param indexPath <#indexPath description#>
 */
- (void)recomposeDataAtIndex:(NSIndexPath *)indexPath
{
    NSUInteger row = indexPath.row;
    NSUInteger section = indexPath.section;
    NSMutableArray *tempArr;
    tempArr = [[NSMutableArray alloc] initWithArray:_dataSourceArr[section]];
    BIDNode *node = _dataSourceArr[section][row];
    if(node.isExpand)
    {
        //展开--》收起--删除数据
        node.isExpand = NO;
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.parentID=%@", node.nodeID];
        NSArray *arr = [tempArr filteredArrayUsingPredicate:predicate];
        [tempArr removeObjectsInArray:arr];
    }
    else
    {
        //收起--》展开--插入数据
        node.isExpand = YES;
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.parentID=%@", node.nodeID];
        NSArray *arr = [_originalArr[section] filteredArrayUsingPredicate:predicate];
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(row+1, arr.count)];
        [tempArr insertObjects:arr atIndexes:indexSet];
    }
    [_dataSourceArr replaceObjectAtIndex:section withObject:tempArr];
    [_tableView reloadData];
}


- (void)alertViewHandler
{
    //交费成功，重新刷新费用列表
    [self loadData];
}

#pragma mark - BIDPayMethodCellDelegate
- (void)selectPayMethodAtIndex:(NSUInteger)index
{
    _selectPayMethod = index;
    _payMethodStateArr = [[NSMutableArray alloc] initWithObjects:@0, @0, @0, nil];
    [_payMethodStateArr replaceObjectAtIndex:index withObject:@1];
    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark - BIDPayCellDelegate
- (void)editSelectStatus:(BOOL)bSelect atIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    BIDNode *node = _dataSourceArr[section][row];
    NSDictionary *dic = node.data;
    if(section != 1) return;
    _isParkFeeChoose = bSelect;
    NSDecimalNumber *decimalnumber = [NSDecimalNumber decimalNumberWithString:ANY2NSSTRING(dic[@"total"])];
    if(bSelect)
    {
        _totalAmount = [_totalAmount decimalNumberByAdding:decimalnumber];
    }
    else
    {
        _totalAmount = [_totalAmount decimalNumberBySubtracting:decimalnumber];
    }
    _amountLabel.text = [[NSString alloc] initWithFormat:@"总计：￥%@元", _totalAmount];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //普通费用、停车费、支付方式
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = nil;
    if(section == 2)
    {
        //支付方式
        arr = _payMethodArr;
    }
    else
    {
        //普通费用、停车费
        arr = _dataSourceArr[section];
    }
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    static NSString *detailIdentifier = @"detailIdentifier";
    static NSString *payMethodIdentifier = @"payMethodIdentifier";
    NSUInteger row = indexPath.row;
    NSUInteger section = indexPath.section;
    if(!_bRegister)
    {
        _bRegister = YES;
        UINib *nib = [UINib nibWithNibName:@"BIDPayCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identifier];
        //
        UINib *nib1 = [UINib nibWithNibName:@"BIDPayDetailCell" bundle:nil];
        [tableView registerNib:nib1 forCellReuseIdentifier:detailIdentifier];
        //
        UINib *nib2 = [UINib nibWithNibName:@"BIDPayMethodCell" bundle:nil];
        [tableView registerNib:nib2 forCellReuseIdentifier:payMethodIdentifier];
    }
    if(section != 2)
    {
        BIDNode *node = _dataSourceArr[section][row];
        //费用列表
        if(node.level==1)
        {
            BIDPayCell *payCell = [tableView dequeueReusableCellWithIdentifier:identifier];
            payCell.delegate = self;
            payCell.indexPath = indexPath;
            NSDictionary *dic = node.data;
            if(section == 1)
            {
                payCell.radioImgView.hidden = NO;
                [payCell updateFeeSelectState:_isParkFeeChoose];
            }
            else
            {
                payCell.radioImgView.hidden = YES;
            }
            //费用类型
            [payCell prepareWithFeeType:dic[@"feeTypeCode"]];
            //费用名字
            payCell.feeNameLabel.text = dic[@"feeTypeName"];
            //费用金额
            payCell.amountLabel.text = [[NSString alloc] initWithFormat:@"￥%@", ANY2NSSTRING(dic[@"total"])];
            //判断该费用是否被锁定
            NSArray *detailFeeArr = dic[@"payFeeList"];
            NSInteger feeStatus = 0;
            for(NSDictionary *dic in detailFeeArr)
            {
                NSNumber *status = dic[@"status"];
                if([status integerValue] == 2)
                {
                    feeStatus = 2;
                    break;
                }
            }
            if(feeStatus == 2)
            {
                _isHaveLockFee = YES;
                //费用被锁定
                [payCell isFeeLock:YES];
            }
            else
            {
                [payCell isFeeLock:NO];
            }
            //
            cell = payCell;
        }
        else
        {
            BIDPayDetailCell *detailCell = [tableView dequeueReusableCellWithIdentifier:detailIdentifier];
            NSDictionary *dic = node.data;
            NSString *strDate = dic[@"feeDate"];
            if(strDate.length==6)
            {
                NSString *strLast = [strDate substringFromIndex:strDate.length-2];
                NSString *strFirst = [strDate substringWithRange:NSMakeRange(0, 4)];
                strDate = [[NSString alloc] initWithFormat:@"%@-%@", strFirst, strLast];
            }
            detailCell.dateLabel.text = strDate;
            detailCell.amountLabel.text = [[NSString alloc] initWithFormat:@"￥%@", dic[@"finalFee"]];
            cell = detailCell;
        }
    }
    else
    {
        //支付方式
        BIDPayMethodCell *payMethodCell = [tableView dequeueReusableCellWithIdentifier:payMethodIdentifier];
        payMethodCell.delegate = self;
        payMethodCell.index = row;
        NSDictionary *dic = _payMethodArr[row];
        payMethodCell.methodImgView.image = [UIImage imageNamed:dic[@"logo"]];
        payMethodCell.titleLabel.text = dic[@"title"];
        NSNumber *value = _payMethodStateArr[row];
        BOOL isSelect = [value intValue]==1 ? YES : NO;
        [payMethodCell updateSelectState:isSelect];
        cell = payMethodCell;
    }
    [cell setBackgroundColor:[UIColor clearColor]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    if(section != 2)
    {
        BIDNode *node = _dataSourceArr[section][row];
        if(node.level == 1)
        {
            [self recomposeDataAtIndex:indexPath];
        }
        else
        {
        }
    }
    else
    {
        //支付方式
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 44.f;
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    if(section == 2)
    {
        height = 44.f;
    }
    else
    {
        BIDNode *node = _dataSourceArr[section][row];
        if(node.level == 1)
        {
            height = 64.f;
        }
        else
        {
            height = 44.f;
        }
    }
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    CGFloat height = 10.f;
    if(section == 2)
    {
        height = 30.f;
    }
    else if(section == 1)
    {
        height = 10.f;
    }
    else
    {
        height = 0.f;
    }
    return height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = nil;
    if(section == 2)
    {
        headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 30.f)];
        [headerView setBackgroundColor:RGBACOLOR(239.f, 239.f, 239.f, 1.f)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16.f, 4.5f, 100.f, 21.f)];
        [label setText:@"支付方式"];
        [label setTextColor:[UIColor darkGrayColor]];
        [label setFont:[UIFont systemFontOfSize:15.f]];
        [headerView addSubview:label];

    }
    else if(section == 1)
    {
        headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 10.f)];
        [headerView setBackgroundColor:RGBACOLOR(239.f, 239.f, 239.f, 1.f)];
    }
    else
    {
    }
    return headerView;
}

@end
